<?php


namespace App\Model;


use App\Constant\Code;
use App\Exception\LogicException;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Hyperf\Guzzle\CoroutineHandler;
use function Swoole\Coroutine\Http\request;

abstract class Model
{
    /**
     * @var Client
     */
    protected $client;

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => 'http://svcs:9502',
            'handler' => HandlerStack::create(new CoroutineHandler()),
            'timeout' => 5,
            'swoole' => [
                'timeout' => 10,
                'socket_buffer_size' => 1024 * 1024 * 2,
            ],
        ]);
    }

    public function get(string $url,array $params = []) :array
    {
        try{
            $response = $this->client->get($url,["query"=>$params]);
            $result = json_decode($response->getBody(),true);
        }catch (\Exception $exception){
            throw new LogicException("接口请求出错",Code::ERROR_SVC_REQUEST);
        }
        return $result;
    }

    public function post(string $url,array $params = []) :array
    {
        try{
            $response = $this->client->get($url,["form_params"=>$params]);
            $result = json_decode($response->getBody(),true);
        }catch (\Exception $exception){
            throw new LogicException("接口请求出错",Code::ERROR_SVC_REQUEST);
        }
        return $result;
    }
}